<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Mapper\ChChannelCodeChangeLogMapper;
use Carbon\Carbon;
use Mine\Abstracts\AbstractService;
use Mine\MineModel;

class ChChannelCodeChangeLogService extends AbstractService
{
    public $mapper;

    public function __construct(ChChannelCodeChangeLogMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function getChannelCodeChangeLog($params): array
    {
        $pageSize = (int)$params['page_size'] ?? MineModel::PAGE_SIZE;
        $query = $this->mapper->model::where('uid',$params['uid'])
            ->when(isset($params['time_range']),function($query) use($params){
                $timeRange = explode(',', $params['time_range']);
                if (count($timeRange) === 2)
                {
                    $start = Carbon::parse(trim($timeRange[0]))->startOfDay();
                    $end = Carbon::parse(trim($timeRange[1]))->endOfDay();
                    $query->whereBetween('created_at', [$start, $end]);
                }
            })
            ->when(isset($params['search']),function($query) use($params){
                $query->where('edit_details','like','%'.$params['search'].'%');
            })
            ->orderBy('created_at','desc')
            ->paginate($pageSize);
        return $this->mapper->setPaginate($query);
    }
}